<template>
  <div class="edit-goods-container" v-loading.lock.lock="fullscreenLoading">
    <div class="edit-form">
      <div class="title">编辑商品信息</div>
      <el-form ref="myForm" :model="form" label-width="100px" :rules="rules">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" clearable> </el-input>
        </el-form-item>
        <!-- 商品分类 -->
        <el-form-item label="商品分类">
          <el-cascader v-model="selectValue" :options="selectOptions" placeholder="请选择商品分类" @change="toggleSelectValue"></el-cascader>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="desc">
          <el-input type="textarea" v-model="form.desc"></el-input>
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格">
          <el-input type="number" v-model="form.price"></el-input>
        </el-form-item>

        <!-- 商品数量 -->
        <el-form-item label="商品数量" prop="count">
          <el-input type="number" v-model="form.count"></el-input>
        </el-form-item>

        <!-- 商品规格 -->
        <el-form-item label="商品规格">
          <el-input v-model="form.specs" :disabled="true"></el-input>
        </el-form-item>

        <!-- 商品货号 -->
        <el-form-item label="商品货号">
          <el-input v-model="form.no" :disabled="true"></el-input>
        </el-form-item>

        <!-- 商品封面图 -->
        <el-form-item label="商品图" prop="src">
          <div class="upload-img" :style="`background-image: url(${form.src});`">
            <input class="upload" type="file" ref="fileEdit" multiple accept="image/gif,image/jpeg,image/jpg,image/png" @change="editHead" />
            <el-icon v-if="form.src === ''"><Plus /></el-icon>
          </div>
        </el-form-item>

        <!-- 是否为店面推荐 -->
        <el-form-item label="是否店面推荐">
          <el-switch v-model="form.recommend"></el-switch>
        </el-form-item>

        <!-- 是否最新 -->
        <el-form-item label="是否最新">
          <el-switch v-model="form.new"></el-switch>
        </el-form-item>

        <!-- 是否轮播 -->
        <el-form-item label="是否轮播">
          <el-switch v-model="form.banner"></el-switch>
        </el-form-item>

        <el-form-item>
          <div style="text-align: center">
            <el-button type="primary" @click="onSubmit" :loading="saveLoading">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'

let validatePass = (rule, value, callback) => {
  if (value <= 0) {
    callback(new Error('商品数量必须大于0'))
  }
}

// 创建路由对象
const router = useRouter()
const route = useRoute()
let saveLoading = ref(false)
let fullscreenLoading = ref(false)
const myForm = ref(null)
let id = route.params.id
let form = reactive({
  name: '',
  cate_id: '',
  desc: '',
  src: '',
  price: 0.0,
  count: 0,
  specs: '',
  no: '',
  recommend: false,
  new: true,
  banner: false
})
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
  ],
  desc: [{ min: 0, max: 500, message: '长度在500以内', trigger: 'blur' }],
  src: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
  count: [{ validator: validatePass, trigger: 'blur' }]
})
let selectValue = ref([]) // 选中的分类数据
let selectOptions = ref([]) // 筛选框中分类数据

// 获取一级分类
const getCateList = async () => {
  try {
    const data = await axios.get('/bus/category/list')
    if (data.code === 0) {
      // 获取一级分类成功
      data.data.forEach((item) => {
        // 遍历一级分类发起请求获取二级分类
        getSonCateList(item)
      })
    } else if (data.msg === '身份认证失败' || data.code === 403) {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 获取二级分类
const getSonCateList = async (item) => {
  const cate = {
    value: item.id,
    label: item.name,
    children: ref([])
  }
  try {
    const data = await axios.get('/bus/category/list/' + item.id)
    if (data.code === 0) {
      // 获取成功
      if (data.data.length > 0) {
        data.data.forEach((cateItem) => {
          cate.children.value.push({
            value: cateItem.id,
            label: cateItem.name
          })
        })
      }
      selectOptions.value.push(cate)
    } else if (data.msg === '身份认证失败' || data.code === 403) {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 分类发生变化
const toggleSelectValue = (val) => {
  form.cate_id = val[1] ? val[1] : val[0]
}

// 上传图片后将图片路径转换为base64
const editHead = (e) => {
  let fileData = e.target.files[0]
  const type = fileData.type.split('/')[1]
  form.img_type = type
  const reader = new FileReader()
  reader.readAsDataURL(fileData)
  reader.onload = (e) => {
    form.src = e.target.result
  }
}

// 表单数据验证
const formValidator = () => {
  // 商品名称不为空
  if (form.name == '') {
    return ElMessage({
      type: 'error',
      message: '请输入商品名称！'
    })
  }
  // 必须选择分类
  if (form.cate_id === '') {
    return ElMessage({
      type: 'error',
      message: '请选择分类！'
    })
  }
  // 商品描述长度不能超过500
  if (form.desc.length > 500) {
    return ElMessage({
      type: 'error',
      message: '商品描述长度不能超过500!'
    })
  }

  // 商品价格必须大于等于0
  if (form.price < 0) {
    return ElMessage({
      type: 'error',
      message: '商品价格必须大于等于0！'
    })
  }

  // 商品数量必须大于0
  if (form.count <= 0) {
    return ElMessage({
      type: 'error',
      message: '商品数量必须大于0！'
    })
  }
  return true
}

// 提交修改的商品信息
const onSubmit = async () => {
  const validatorRes = formValidator()
  if (validatorRes === true) {
    saveLoading = true
    // 发起请求添加商品
    const data = await axios.post('/bus/edit/goods/' + id, {
      name: form.name,
      cate_id: form.cate_id,
      desc: form.desc,
      price: form.price,
      count: form.count,
      specs: form.specs,
      no: form.no,
      recommend: form.recommend,
      new: form.new,
      banner: form.banner
    })
    saveLoading = false
    if (data.code === 0) {
      // 上传成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      router.back()
    } else if (data.msg === '身份验证失败！') {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      // 删除本地token
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  }
}
// 根据id获取商品信息
const getGoodsInfo = async () => {
  fullscreenLoading.value = true
  try {
    const data = await axios.get('/bus/goods/' + id)
    if (data.code === 0) {
      // 获取商品信息成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 商品信息
      form.name = data.data.goods_name
      form.cate_id = data.data.cate_id
      form.desc = data.data.goods_desc
      form.src = 'http://127.0.0.1:5500' + data.data.goods_img
      form.price = data.data.goods_price
      form.count = data.data.goods_stock
      form.specs = data.data.specs
      form.no = data.data.article_no
      form.recommend = data.data.is_recommend === '1' ? true : false
      form.new = data.data.is_new === '1' ? true : false
      form.banner = data.data.is_banner === '1' ? true : false
      selectValue.value = data.data.cate_arr
    } else if (data.code === 403 || data.msg === '身份验证失败') {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    console.log(form)
    fullscreenLoading.value = false
  }
}
// 发起请求获取分类
getCateList()
getGoodsInfo()
</script>

<style lang="scss" scoped>
.edit-goods-container {
  .edit-form {
    margin: 50px auto;
    border: 1px solid #e1e1e1;
    width: 860px;
    padding: 50px 100px 0;
    box-sizing: border-box;

    .title {
      font-size: 24px;
      font-weight: 700;
      color: #606266;
      text-align: center;
      margin-bottom: 50px;
    }
    .upload-img {
      border: 1px dashed #e1e1e1;
      height: 80px;
      width: 80px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .upload {
        position: absolute;
        height: 100%;
        width: 100%;
        z-index: 999;
        opacity: 0;
      }

      .el-icon {
        font-size: 24px;
        color: #e1e1e1;
      }
    }
  }
}
</style>
